package com.nnnu.wsnackshop.controller.admin;

import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.RiderDTO;
import com.nnnu.wsnackshop.pojo.dto.RiderStatusDTO;
import com.nnnu.wsnackshop.pojo.entity.Riders;
import com.nnnu.wsnackshop.pojo.vo.RiderStatsVO;
import com.nnnu.wsnackshop.pojo.vo.RiderVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IRidersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员端-骑手 前端控制器
 * </p>
 */
@RestController("adminRidersController")
@RequestMapping("/api/admin/riders")
@Tag(name = "管理员端-骑手接口")
@Slf4j
@RequiresRoles(value = { "admin", "superAdmin" }, logical = Logical.OR)
@RequiredArgsConstructor
public class RidersController extends BaseController {

    private final IRidersService ridersService;

    /**
     * 获取骑手列表
     */
    @GetMapping
    @Operation(summary = "获取骑手列表", description = "管理员获取骑手分页列表")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<PageResult<RiderVO>> getRiders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone) {
        log.info("[管理员] 获取骑手列表: page={}, pageSize={}, name={}, phone={}", page, pageSize, name, phone);

        PageResult<RiderVO> pageResult = ridersService.getRiderList(page, pageSize, name, phone);
        log.info("[管理员] 返回骑手列表: total={}, size={}", pageResult.getTotal(), pageResult.getItems().size());

        return Result.success(pageResult);
    }

    /**
     * 获取可用骑手列表
     */
    @GetMapping("/available")
    @Operation(summary = "获取可用骑手列表", description = "管理员获取可用骑手列表（状态为在线且未达到10单上限的骑手）")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<List<RiderVO>> getAvailableRiders() {
        log.info("[管理员] 获取可用骑手列表");

        // 获取所有骑手
        List<Riders> allRiders = ridersService.list();
        List<RiderVO> availableRiders = new ArrayList<>();

        // 遍历骑手，过滤出可用骑手
        for (Riders rider : allRiders) {
            if (rider.getStatus() != 0) { // 不是离线状态
                RiderVO riderVO = ridersService.getRiderDetail(rider.getId());
                if (riderVO.getCurrentOrderCount() < 10) {
                    availableRiders.add(riderVO);
                }
            }
        }

        return Result.success(availableRiders);
    }

    /**
     * 获取骑手详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取骑手详情", description = "管理员获取骑手详情")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<RiderVO> getRiderDetail(@PathVariable("id") Integer riderId) {
        log.info("[管理员] 获取骑手详情, riderId: {}", riderId);
        RiderVO riderVO = ridersService.getRiderDetail(riderId);
        return Result.success(riderVO);
    }

    /**
     * 更新骑手状态
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "更新骑手状态", description = "管理员更新骑手状态")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("rider:manage")
    public Result<Boolean> updateRiderStatus(
            @PathVariable Integer id,
            @RequestBody Map<String, Integer> requestBody) {

        Integer status = requestBody.get("status");
        if (status == null) {
            return Result.error(400, "状态不能为空");
        }

        log.info("管理员更新骑手状态: riderId={}, status={}", id, status);
        boolean success = ridersService.updateRiderStatus(id, status);
        return Result.success(success, "更新骑手状态成功");
    }

    /**
     * 获取骑手订单列表
     */
    @GetMapping("/{id}/orders")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @Operation(summary = "获取骑手订单列表", description = "管理员获取骑手订单列表")
    public Result<PageResult<Map<String, Object>>> getRiderOrders(
            @PathVariable Integer id,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        log.info("获取骑手订单列表: id={}, status={}, page={}, pageSize={}", id, status, page, pageSize);
        PageResult<Map<String, Object>> orders = ridersService.getRiderOrders(id, status, page, pageSize);
        return Result.success(orders);
    }

    /**
     * 添加骑手
     */
    @PostMapping
    @Operation(summary = "添加骑手", description = "管理员添加骑手")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("rider:add")
    public Result<RiderVO> addRider(@RequestBody RiderDTO riderDTO) {
        log.info("管理员添加骑手: {}", riderDTO);
        Riders rider = ridersService.addRider(riderDTO);
        RiderVO riderVO = ridersService.getRiderDetail(rider.getId());
        return Result.success(riderVO, "添加骑手成功");
    }

    /**
     * 更新骑手信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新骑手信息", description = "管理员更新骑手信息")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("rider:edit")
    public Result<Boolean> updateRider(
            @PathVariable Integer id,
            @RequestBody RiderDTO riderDTO) {

        log.info("管理员更新骑手信息: id={}, rider={}", id, riderDTO);
        riderDTO.setId(id);
        boolean success = ridersService.updateRider(riderDTO);
        return Result.success(success, "更新骑手信息成功");
    }

    /**
     * 删除骑手
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除骑手", description = "管理员删除骑手")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("rider:delete")
    public Result<Boolean> deleteRider(@PathVariable Integer id) {
        log.info("管理员删除骑手: id={}", id);
        boolean success = ridersService.removeById(id);
        return Result.success(success, "删除骑手成功");
    }

    /**
     * 获取骑手配送历史
     */
    @GetMapping("/{id}/history")
    @Operation(summary = "获取骑手配送历史", description = "管理员获取骑手配送历史")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<PageResult<Map<String, Object>>> getRiderDeliveryHistory(
            @PathVariable Integer id,
            @RequestParam(required = false) String timeRange,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        log.info("获取骑手配送历史: id={}, timeRange={}, page={}, pageSize={}", id, timeRange, page, pageSize);
        PageResult<Map<String, Object>> deliveries = ridersService.getRiderDeliveryHistory(id, timeRange, page,
                pageSize);
        return Result.success(deliveries);
    }

    /**
     * 获取骑手统计数据
     */
    @GetMapping("/{id}/stats")
    @Operation(summary = "获取骑手统计数据", description = "管理员获取骑手统计数据")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<RiderStatsVO> getRiderStats(@PathVariable Integer id) {
        log.info("获取骑手统计数据: id={}", id);
        RiderStatsVO stats = ridersService.getRiderStats(id);
        return Result.success(stats);
    }
}